<template>
  <u-upload :fileList="fileList" @afterRead="afterRead($event)" @delete="deletePic($event)"></u-upload>
</template>

<script lang="ts" setup>
import { fileUpload } from '@/apis';
import { ref } from 'vue';

const { modelValue } = defineProps<{ modelValue: string }>()
const emit = defineEmits<{ (event: "update:modelValue", name: string): void }>()

const fileList = ref<any[]>([])

const deletePic = (event: { index: number; }) => {
  fileList.value.splice(event.index, 1);
};

const afterRead = async (event: { file: ConcatArray<never>; }) => {
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists: any[] = [].concat(event.file);
  let fileListLen = fileList.value.length;
  lists.map((item: any) => {
    fileList.value.push({
      ...item,
      status: 'uploading',
      message: '上传中',
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const { data } = await fileUpload(lists[i].url)
    let item = fileList.value[fileListLen];
    fileList.value.splice(fileListLen, 1, {
      ...item,
      status: 'success',
      message: '',
      url: data.uuid,
    });
    fileListLen++;
  }
  
  emit('update:modelValue', fileList.value.map(item => item.url).toString())
};
</script>